package org.aphelie.torg.ruler.internal.ui.editor.character.actions;

import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;

import org.aphelie.torg.ruler.core.IBaseModel;
import org.aphelie.torg.ruler.core.character.ICharacterBase;
import org.aphelie.torg.ruler.core.character.ICharacterModelBase;
import org.aphelie.torg.ruler.internal.core.text.character.CharacterBaseNode;
import org.aphelie.torg.ruler.internal.ui.TGRUIMessages;
import org.aphelie.torg.ruler.internal.ui.util.ModelModification;
import org.aphelie.torg.ruler.internal.ui.util.TGRModelUtility;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ui.IFileEditorInput;
import org.osgi.framework.Bundle;

public class FormatOperation implements IRunnableWithProgress {

	private Object[] fObjects;

	public FormatOperation(Object[] objects) {
		fObjects = objects;
	}

	public void run(IProgressMonitor mon) throws InvocationTargetException, InterruptedException {
		mon.beginTask(TGRUIMessages.FormatManifestOperation_task, fObjects.length);
		for (int i = 0; !mon.isCanceled() && i < fObjects.length; i++) {
			Object obj = fObjects[i];
			if (obj instanceof IFileEditorInput)
				obj = ((IFileEditorInput) obj).getFile();
			if (obj instanceof IFile) {
				mon.subTask(NLS.bind(TGRUIMessages.FormatManifestOperation_subtask, ((IFile) obj).getFullPath().toString()));
				format((IFile) obj, mon);
			}
			mon.worked(1);
		}
	}

	public static void format(IFile file, IProgressMonitor mon) {
		TGRModelUtility.modifyModel(new ModelModification(file) {
			protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException {
				//if (model instanceof IBundleCharacterModelBase) {
					//IBundleModel bundleModel = ((IBundleCharacterModelBase) model).getBundleModel();
					//if (bundleModel.getBundle() instanceof Bundle)
						//formatBundle((Bundle) bundleModel.getBundle());
				//} else if (model instanceof ICharacterModelBase) {
					ICharacterBase pluginModel = ((ICharacterModelBase) model).getCharacterBase();
					if (pluginModel instanceof CharacterBaseNode)
						formatXML((CharacterBaseNode) pluginModel);
				//}
			}

			public boolean saveOpenEditor() {
				return false;
			}
		}, mon);
	}

	/*
	private static void formatBundle(Bundle bundle) {
		Iterator headers = bundle.getHeaders().values().iterator();
		while (headers.hasNext())
			((IManifestHeader) headers.next()).update(true);
		BundleModel model = (BundleModel) bundle.getModel();
		model.adjustOffsets(model.getDocument());
	}
	*/

	private static void formatXML(CharacterBaseNode node) {
		// TODO Auto-generated method stub

	}

}
